package util

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"gitee.com/snxamdf/wui/logs"
	htmlTemplate "html/template"
	"strconv"
	"strings"
	textTemplate "text/template"
	"time"
)

func Sleep(s time.Duration) {
	time.Sleep(time.Second * s)
}

func HtmlTemplateBuffer(template *htmlTemplate.Template, data interface{}) (*bytes.Buffer, error) {
	buf := &bytes.Buffer{}
	if err := template.Execute(buf, data); err != nil {
		logs.Error("HtmlTemplate Error", err)
		return nil, err
	}
	return buf, nil
}

func HtmlTemplate(template *htmlTemplate.Template, data interface{}) (string, error) {
	buf, err := HtmlTemplateBuffer(template, data)
	return buf.String(), err
}

func TextTemplate(template *textTemplate.Template, data interface{}) (string, error) {
	buf := &bytes.Buffer{}
	if err := template.Execute(buf, data); err != nil {
		logs.Error("HtmlTemplate Error", err)
		return "", err
	}
	return buf.String(), nil
}

func IsBlank(value ...string) bool {
	for _, v := range value {
		if v == "" || strings.Trim(v, " ") == "" || v == "null" || &v == nil {
			return true
		}
	}
	return false
}

//毫秒级
func GetTimeStamp() int64 {
	return time.Now().UnixNano() / 1e6
}

//纳秒级
func GetTimeStampUnixNano() int64 {
	return time.Now().UnixNano()
}

//字符串纳秒级
func GetID() string {
	return fmt.Sprintf("%d", GetTimeStampUnixNano())
}

//纳秒级MD5
func GetMD5ID() string {
	return MD5(fmt.Sprintf("%d", GetTimeStampUnixNano()))
}

func ParseString(value interface{}) string {
	switch value.(type) {
	case string:
		return value.(string)
	case int, int64, int32:
		return fmt.Sprintf("%d", value)
	case float32, float64:
		return fmt.Sprintf("%f", value)
	case bool:
		return strconv.FormatBool(value.(bool))
	case byte:
		return fmt.Sprintf("%c", value)
	case []byte:
		return fmt.Sprintf("%d", BytesToInt(value.([]byte)))
	case map[string]interface{}, []interface{}, []map[string]interface{}, interface{}:
		if r, err := ToJson(value); err != nil {
			logs.Error("ParseString [value.type=map[string]interface{}] error:", err)
		} else {
			return string(r)
		}

	}
	return ""
}

func ParseInt(value interface{}) int {
	switch value.(type) {
	case bool:
		if value.(bool) {
			return 1
		}
		return 0
	case byte:
		return int(value.(byte))
	case []byte:
		return BytesToInt(value.([]byte))
	}
	p := ParseString(value)
	if p == "" {
		return 0
	}
	if r, err := strconv.Atoi(p); err != nil {
		return 0
	} else {
		return r
	}
}

func BytesToInt(b []byte) int {
	bytesBuffer := bytes.NewBuffer(b)
	var x int32
	err := binary.Read(bytesBuffer, binary.BigEndian, &x)
	if err != nil {
		return 0
	}
	return int(x)
}
